package cn.edu.scnu.thewonderofink.component.banner

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import cn.edu.scnu.thewonderofink.databinding.BannerBinding
import cn.edu.scnu.thewonderofink.ui.home.BannerAdapter


/**
 * @说明 Item是从0开始计算的，与数组是相同的
 */


class Banner @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    private var binding : BannerBinding
    private var bannerAdapter : BannerAdapter


    private val viewPagerHandler = Handler(Looper.getMainLooper())
    private var viewPagerRunnable : Runnable
    private var listener : ((currentPage: Int) -> Unit) ?= null

    private val mData = ArrayList<Int>()

    init {
        binding = BannerBinding.inflate(LayoutInflater.from(context), this)
        bannerAdapter = BannerAdapter(mData)
        binding.viewPager.adapter = bannerAdapter

        val pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
            private var lastPage = mData.size - 1

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                // 当viewPager切换时，同时计算tab的切换
                val total = (binding.viewPager.adapter?.itemCount ?: 0)
                val curPosition = if (total > 1 && position >= 0 && position < 3) {
                    position
                } else {
                    null
                }
                if (curPosition != null && lastPage != curPosition) {
                    listener?.invoke(curPosition)
                    binding.indicatorLayout.getTabAt(curPosition)?.select()
                    lastPage = curPosition
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)

                // 当滑动到最后一张图片时，切换到第一张图片
                val total = (binding.viewPager.adapter?.itemCount ?: 0)
                if (state == ViewPager2.SCROLL_STATE_IDLE && total > 1 && binding.viewPager.currentItem == total - 1) {
                    binding.viewPager.setCurrentItem(0, false)
                }
                // 当滑动到第一张图片时，切换到最后一张图片
                if (state == ViewPager2.SCROLL_STATE_IDLE && total > 1 && binding.viewPager.currentItem == 0) {
                    binding.viewPager.setCurrentItem(total - 1, false)
                }
            }

        }

        binding.viewPager.registerOnPageChangeCallback(pageChangeCallback)

        viewPagerRunnable = object : Runnable{
            override fun run() {
                binding.viewPager.apply {
                    if(currentItem + 1 < (adapter?.itemCount ?: 0)){
                        setCurrentItem(currentItem + 1, false)
                    }
                    else if(currentItem + 1 == (adapter?.itemCount ?: 0))
                    {
                        setCurrentItem(0, false)
                    }
                }
                viewPagerHandler.postDelayed(this, 3000)
            }
        }
    }

    // TODO: 设置item点击处理，需要在adapter中也添加SetOnClickListener


    // todo: 设置页面切换时的监听

    /**
     * @author 沈思嘉
     * @date 2023/04/09
     * @param bannerData 整个banner框中的图片id列表
     * @return None 用于更新banner框中的图片
     */
    fun updateData(bannerData: List<Int>) {
        mData.clear()
        mData.addAll(bannerData)
        if (mData.size > 1) {
            // 默认展示第一张图
            binding.viewPager.setCurrentItem(0, false)
            // 初始化下方圆点指示器
            binding.indicatorLayout.removeAllTabs()
            for (i in 0 until mData.size) {
                val tab = binding.indicatorLayout.newTab()
                tab.view.isEnabled = false
                binding.indicatorLayout.addTab(tab)
            }
        } else {
            binding.indicatorLayout.removeAllTabs()
        }
        binding.viewPager.adapter?.notifyDataSetChanged()
    }

    /**
     * 设置视图是否自动滚动轮播
     * @param autoScroll Boolean 是否自动滚动
     */
    fun autoScroll(autoScroll:Boolean){
        viewPagerHandler.removeCallbacks(viewPagerRunnable)
        if(autoScroll) {
            viewPagerHandler.postDelayed(viewPagerRunnable, 3000)
        }
    }
}